﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Repositories;
using SqlSugar;

namespace Infrastructure.UnitWork
{
    public class UnitOfWork : IUnitOfWork
    {
        public SqlSugarScope SqlSugarScope { get; init; }

        private SugarUnitOfWork sugarUnitOfWork;

        public UnitOfWork(ISqlSugarClient sqlSugarClient)
        {
            SqlSugarScope = sqlSugarClient as SqlSugarScope;
        }

        public void BeginTran()
        {
            SqlSugarScope.BeginTran();
        }

        public void CommitTran()
        {
            try
            {
                SqlSugarScope.CommitTran();
            }
            catch
            {
                SqlSugarScope.RollbackTran();
                throw;
            }
        }

        public void RollbackTran()
        {
            SqlSugarScope.RollbackTran();
        }

        public void BeginUnitOfWork()
        {
            sugarUnitOfWork = SqlSugarScope.CreateContext();
        }

        public void CommitUnitOfWork()
        {
            sugarUnitOfWork?.Commit();
            DisposeUnitOfWork();
        }

        public void DisposeUnitOfWork()
        {
            sugarUnitOfWork?.Dispose();
        }
    }
}
